const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs-extra');
const { createApp } = require('./create-app');
const { publishApp } = require('./publish-app');
const { buildApp } = require('./build-app');
const { login } = require('./login');
const { getTemplates } = require('./templates');
const { v4: uuidv4 } = require('uuid');

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../public')));

// 配置文件路径
const CONFIG_DIR = path.join(process.env.HOME || process.env.USERPROFILE, '.simple-tools');
const APPS_FILE = path.join(CONFIG_DIR, 'apps.json');
const TOKEN_FILE = path.join(CONFIG_DIR, 'token.json');

// 确保配置目录存在
async function ensureConfigDir() {
    await fs.ensureDir(CONFIG_DIR);
}

// 保存应用列表
async function saveApps(apps) {
    await ensureConfigDir();
    await fs.writeJson(APPS_FILE, apps, { spaces: 2 });
}

// 读取应用列表
async function loadAppsFromConfig() {
    try {
        await ensureConfigDir();
        if (await fs.pathExists(APPS_FILE)) {
            return await fs.readJson(APPS_FILE);
        }
        return [];
    } catch (error) {
        console.error('读取应用列表失败:', error);
        return [];
    }
}

// 检查登录状态
app.get('/api/check-login', async (req, res) => {
    try {
        if (await fs.pathExists(TOKEN_FILE)) {
            const token = await fs.readJson(TOKEN_FILE);
            if (token && token.expiresAt > Date.now()) {
                res.json({ success: true });
            } else {
                await fs.remove(TOKEN_FILE);
                res.json({ success: false });
            }
        } else {
            res.json({ success: false });
        }
    } catch (error) {
        res.json({ success: false });
    }
});

// 登录
app.post('/api/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        const token = await login(username, password);
        
        // 保存token
        await ensureConfigDir();
        await fs.writeJson(TOKEN_FILE, {
            token,
            expiresAt: Date.now() + 24 * 60 * 60 * 1000 // 24小时后过期
        });
        
        res.json({ success: true });
    } catch (error) {
        res.status(401).json({ success: false, error: error.message });
    }
});

// 退出登录
app.post('/api/logout', async (req, res) => {
    try {
        if (await fs.pathExists(TOKEN_FILE)) {
            await fs.remove(TOKEN_FILE);
        }
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取应用列表
app.get('/api/apps', async (req, res) => {
    try {
        const apps = await loadAppsFromConfig();
        res.json({ success: true, apps });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取文件系统
app.get('/api/filesystem', async (req, res) => {
    try {
        const { path: dirPath } = req.query;
        const files = await getFileSystem(dirPath);
        res.json({ success: true, files });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 删除应用
app.delete('/api/apps/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const apps = await loadAppsFromConfig();
        const appIndex = apps.findIndex(app => app.id === id);
        
        if (appIndex !== -1) {
            const app = apps[appIndex];
            await fs.remove(app.path);
            apps.splice(appIndex, 1);
            await saveApps(apps);
            res.json({ success: true });
        } else {
            res.status(404).json({ success: false, error: '应用不存在' });
        }
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 移除应用（保留文件）
app.post('/api/apps/:id/remove', async (req, res) => {
    try {
        const { id } = req.params;
        const apps = await loadAppsFromConfig();
        const appIndex = apps.findIndex(app => app.id === id);
        
        if (appIndex !== -1) {
            apps.splice(appIndex, 1);
            await saveApps(apps);
            res.json({ success: true });
        } else {
            res.status(404).json({ success: false, error: '应用不存在' });
        }
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取模板列表
app.get('/api/templates', async (req, res) => {
    try {
        const templates = await getTemplates();
        res.json({ success: true, templates });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 创建应用
app.post('/api/create-app', async (req, res) => {
    try {
        const {
            name,
            projectName,
            description,
            version,
            author,
            location,
            template
         } = req.body;
        await createApp(path.join(location, projectName), {
            name,
            description,
            version,
            author,
            template
        });
        
        // 添加到应用列表
        const apps = await loadAppsFromConfig();
        apps.push({
            id: uuidv4(),
            name,
            projectName,
            description,
            version,
            author,
            path: location,
            template,
            createdAt: new Date(),
            updatedAt: new Date()
        });
        await saveApps(apps);
        
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 打包应用
app.post('/api/build-app', async (req, res) => {
    try {
        const { id } = req.body;
        const apps = await loadAppsFromConfig();
        const app = apps.find(app => app.id === id);
        
        if (!app) {
            return res.status(404).json({ success: false, error: '应用不存在' });
        }
        
        await buildApp(app.path);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 发布应用
app.post('/api/publish-app', async (req, res) => {
    try {
        const { id } = req.body;
        const apps = await loadAppsFromConfig();
        const app = apps.find(app => app.id === id);
        
        if (!app) {
            return res.status(404).json({ success: false, error: '应用不存在' });
        }
        
        await publishApp(app.path);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取应用详情
app.get('/api/apps/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const apps = await loadAppsFromConfig();
        const app = apps.find(app => app.id === id);
        
        if (!app) {
            return res.status(404).json({ success: false, error: '应用不存在' });
        }

        // 读取应用配置文件
        const configPath = path.join(app.path, 'app.json');
        let appConfig = {};
        if (fs.existsSync(configPath)) {
            appConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
        }

        res.json({
            success: true,
            app: {
                id: app.id,
                name: app.name,
                projectName: app.projectName,
                description: app.description,
                version: app.version,
                author: app.author,
                location: app.path
            }
        });
    } catch (error) {
        res.json({ success: false, error: error.message });
    }
});

// 获取应用内容
app.get('/api/apps/:id/content', async (req, res) => {
    try {
        const { id } = req.params;
        const apps = await loadAppsFromConfig();
        const app = apps.find(app => app.id === id);
        
        if (!app) {
            return res.status(404).json({ success: false, error: '应用不存在' });
        }

        // 读取应用文件内容
        const templatePath = path.join(app.path, 'template.html');
        const scriptPath = path.join(app.path, 'script.js');
        const stylePath = path.join(app.path, 'style.css');

        const content = {
            template: fs.existsSync(templatePath) ? fs.readFileSync(templatePath, 'utf8') : '',
            script: fs.existsSync(scriptPath) ? fs.readFileSync(scriptPath, 'utf8') : '',
            style: fs.existsSync(stylePath) ? fs.readFileSync(stylePath, 'utf8') : ''
        };

        res.json({
            success: true,
            content
        });
    } catch (error) {
        res.json({ success: false, error: error.message });
    }
});

// 保存应用内容
app.post('/api/apps/:id/content', async (req, res) => {
    try {
        const { id } = req.params;
        const { template, script, style } = req.body;
        const apps = await loadAppsFromConfig();
        const app = apps.find(app => app.id === id);
        
        if (!app) {
            return res.status(404).json({ success: false, error: '应用不存在' });
        }

        // 保存应用文件内容
        const templatePath = path.join(app.path, 'template.html');
        const scriptPath = path.join(app.path, 'script.js');
        const stylePath = path.join(app.path, 'style.css');

        if (template !== undefined) {
            fs.writeFileSync(templatePath, template);
        }
        if (script !== undefined) {
            fs.writeFileSync(scriptPath, script);
        }
        if (style !== undefined) {
            fs.writeFileSync(stylePath, style);
        }

        // 更新应用缓存中的更新时间
        app.updatedAt = new Date();
        await saveApps(apps);

        res.json({
            success: true,
            message: '保存成功'
        });
    } catch (error) {
        res.json({ success: false, error: error.message });
    }
});

// 启动服务器
const startDevServer = (port = 3000) => {
    return new Promise((resolve, reject) => {
        app.listen(port, () => {
            console.log(`可视化应用管理器已启动，访问 http://localhost:${port}`);
            resolve();
        }).on('error', reject);
    });
};

// 获取文件系统
async function getFileSystem(dirPath) {
    try {
        // 如果dirPath是空字符串，使用当前工作目录
        const targetPath = dirPath || process.cwd();
        
        const stats = await fs.stat(targetPath);
        if (!stats.isDirectory()) {
            throw new Error('Not a directory');
        }

        const items = await fs.readdir(targetPath);
        const files = await Promise.all(items.map(async (item) => {
            const itemPath = path.join(targetPath, item);
            const stats = await fs.stat(itemPath);
            return {
                name: item,
                path: itemPath, // 返回绝对路径
                isDirectory: stats.isDirectory(),
                size: stats.size,
                createdAt: stats.birthtime,
                updatedAt: stats.mtime
            };
        }));

        return {
            currentPath: targetPath, // 返回绝对路径
            parentPath: path.dirname(targetPath), // 返回父目录的绝对路径
            files
        };
    } catch (error) {
        throw new Error('Invalid path');
    }
}

module.exports = {
    startDevServer
}; 